package com.xbh.Book.web;

import com.xbh.Book.pojo.Cart;
import com.xbh.Book.pojo.User;
import com.xbh.Book.service.OrderService;
import com.xbh.Book.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: JavaWebExer
 * @description:
 * @author: 许宝华
 * @create: 2021-05-03 15:21
 */

public class OrderServlet extends BaseServlet{
    private OrderService orderService=new OrderServiceImpl();
    /**
     * 生成订单
     * @param req
     * @param resp
     * @return void
     * @author 许宝华
     * @creed: Talk is cheap,show me the code
     * @date 2021/5/3 15:22
     */
    protected void createOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //先获取cart购物车对象
        Cart cart=(Cart) req.getSession().getAttribute("cart");
        //获取userId
        User loginUser = (User) req.getSession().getAttribute("user");
        if(loginUser==null){
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
            return;
        }
        Integer userId = loginUser.getId();
        //调用orderService。createOrder(cart,userId):生成订单

        String orderId = orderService.createOrder(cart, userId);
        req.getSession().setAttribute("orderId",orderId);
//        req.setAttribute("orderId",orderId);
        //请求转发会引发表单重复提交，使用重定向,但是重定向不支持request域的数据共享，所以要保存到session域中
//        req.getRequestDispatcher("/pages/cart/checkout.jsp").forward(req,resp);
        resp.sendRedirect(req.getContextPath()+"/pages/cart/checkout.jsp");
    }
}
